package com.bodacn.keypoint;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bodacn.keypoint.adapter.ClothPieceGrAdapter;
import com.bodacn.keypoint.adapter.ClothPieceSearchGrAdapter;
import com.bodacn.keypoint.adapter.ClothPieceSearchLeftLvAdapter;
import com.bodacn.keypoint.adapter.ClothPieceSearchRightLvAdapter;
import com.bodacn.keypoint.adapter.ClothSizeSearchRightLvAdapter;
import com.bodacn.keypoint.bean.ClothPieceCheckLeft;
import com.bodacn.keypoint.bean.ClothPieceCheckRight;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClothSizeSearchActivity extends AppCompatActivity {

    @BindView(R.id.edit_startDate)
    EditText editStartDate;
    @BindView(R.id.edit_endDate)
    EditText editEndDate;
    @BindView(R.id.edit_findOrderNo)
    EditText editFindOrderNo;
    @BindView(R.id.btn_find)
    Button btnFind;
    @BindView(R.id.btn_Close)
    Button btnClose;
    @BindView(R.id.tv_data)
    TextView tvData;
    @BindView(R.id.tv_hyh)
    TextView tvHyh;
    @BindView(R.id.tv_huohao)
    TextView tvHuohao;
    @BindView(R.id.tv_po)
    TextView tvPo;
    @BindView(R.id.tv_size)
    TextView tvSize;
    @BindView(R.id.tv_style)
    TextView tvStyle;
    @BindView(R.id.tv_color)
    TextView tvColor;
    @BindView(R.id.lv_left)
    ListView lvLeft;
    @BindView(R.id.tv_PartName)
    TextView tvPartName;
    @BindView(R.id.tv_NormalSize)
    TextView tvNormalSize;
    @BindView(R.id.tv_realSize)
    TextView tvRealSize;
    @BindView(R.id.mylistitem)
    LinearLayout mylistitem;
    @BindView(R.id.lv_right)
    ListView lvRight;
    String curLoginUserNo = "", curDepartNo = "";
    private final int MSG_DetailOver = 1001;
    private final int MSG_DetaiInfoOver = 1003;
    private final int MSG_ErrMessage = 1002;
    private final int MSG_DetailDEOver = 1004;
    JSONArray detailJSON;
    List<ClothPieceCheckLeft> lefts = new ArrayList<>();
    List<ClothPieceCheckRight> rights = new ArrayList<>();
    ClothPieceSearchLeftLvAdapter clothPieceSearchLeftLvAdapter;
    ClothSizeSearchRightLvAdapter clothPieceSearchRightLvAdapter;
    @BindView(R.id.gr)
    GridView gr;
    private ClothPieceSearchGrAdapter grAdapter;
    String DepartmentNo = "", StartDate = "", EndDate = "", OrderNo = "", UserNo = "", OrderId = "",
            WorkDate = "", StyleNo = "", PO = "", Color = "", Size = "", StyleSort = "",SerNo ="";
    private List<String> grString = new ArrayList<>();
    private List<String> grOrderIdString = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cloth_size_search);
        ButterKnife.bind(this);
        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        String StartDateStr = (String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
        String EndDateStr = (String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
        editStartDate.setText(StartDateStr);
        editEndDate.setText(EndDateStr);
        Bundle paramBundle = this.getIntent().getExtras();
        if (paramBundle != null) {
            curLoginUserNo = paramBundle.getString("LoginUserNo");
            curDepartNo = paramBundle.getString("curDepartNo");
        }

        clothPieceSearchLeftLvAdapter = new ClothPieceSearchLeftLvAdapter(lefts, this);
        lvLeft.setAdapter(clothPieceSearchLeftLvAdapter);
        lvLeft.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OrderId = lefts.get(position).getOrderId();
                WorkDate = lefts.get(position).getAddDate();
                PO = lefts.get(position).getPO();
                StyleNo = lefts.get(position).getGoodsNo();
                Size = lefts.get(position).getSize();
                StyleSort = lefts.get(position).getStyle();
                Color = lefts.get(position).getColor();
                refreshOrderList("GetOrderDe");
            }
        });


        gr.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OrderId = grOrderIdString.get(position);
                SerNo= grString.get(position);
                refreshOrderList("GetOrderInfo");
            }
        });

    }

    @OnClick({R.id.edit_startDate, R.id.edit_endDate, R.id.btn_find, R.id.btn_Close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.edit_startDate:
                final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(view.getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.Finish), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year, month, day);
                        editStartDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.Cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle(getString(R.string.PleaseSelectQueryDate));
                mDialog.show();
                break;
            case R.id.edit_endDate:
                final Calendar calendar1 = Calendar.getInstance();
                final DatePickerDialog mDialog1 = new DatePickerDialog(view.getContext(), null, calendar1.get(Calendar.YEAR), calendar1.get(Calendar.MONTH), calendar1.get(Calendar.DAY_OF_MONTH));
                mDialog1.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.Finish), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog1.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar1.set(year, month, day);
                        editEndDate.setText(DateFormat.format("yyyy-MM-dd", calendar1));
                    }
                });
                mDialog1.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.Cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog1.setTitle(getString(R.string.PleaseSelectQueryDate));
                mDialog1.show();
                break;
            case R.id.btn_find:
                UserNo = "";
                OrderId = "";
                WorkDate = "";
                StyleNo = "";
                PO = "";
                Color = "";
                Size = "";
                StyleSort = "";
                SerNo = "";
                lvRight.setAdapter(null);
                gr.setAdapter(null);
                refreshOrderList("GetOrder");
                break;
            case R.id.btn_Close:
                finish();
                break;
        }
    }

    private void refreshOrderList(String OperType) {
        OrderNo = editFindOrderNo.getText().toString();
        StartDate = editStartDate.getText().toString();
        EndDate = editEndDate.getText().toString();
        String sqlCmd = "Exec ScenePAD_PieceSizeGetOrder  @OperType='" + OperType + "',@DepartmentNo ='" + DepartmentNo + "',@StartDate ='" + StartDate + "',@EndDate ='" + EndDate + "'," +
                "@OrderNo ='" + OrderNo + "',@UserNo ='" + curLoginUserNo + "',@OrderId ='" + OrderId + "',@WorkDate ='" + WorkDate + "',@StyleNo ='" + StyleNo + "',@PO ='" + PO + "',@Color ='" + Color + "'," +
                "@Size ='" + Size + "',@StyleSort ='" + StyleSort + "' ,@SerNo='"+SerNo+"'";
        Log.e("SQL", sqlCmd);
        ReadSQLData(sqlCmd);
    }


    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_DetailOver:
                    //显示到orderListGrid中;
                    if (detailJSON != null && detailJSON.length() > 0) {
                        List<ClothPieceCheckLeft> clothPieceCheckLefts = new Gson().fromJson(String.valueOf(detailJSON), new TypeToken<List<ClothPieceCheckLeft>>() {
                        }.getType());
                        if (clothPieceCheckLefts != null) {
                            lefts.clear();
                            lefts.addAll(clothPieceCheckLefts);
                            clothPieceSearchLeftLvAdapter.notifyDataSetChanged();
                        }
                    } else {
                        lefts.clear();
                        clothPieceSearchLeftLvAdapter.notifyDataSetChanged();
                        gr.setAdapter(null);
                        lvRight.setAdapter(null);
                    }
                    break;
                case MSG_DetailDEOver:
                    if (detailJSON != null && detailJSON.length() > 0) {
                        List<ClothPieceCheckRight> clothPieceCheckRights = new Gson().fromJson(String.valueOf(detailJSON), new TypeToken<List<ClothPieceCheckRight>>() {
                        }.getType());
                        if (clothPieceCheckRights != null) {
                            grString.clear();
                            grOrderIdString.clear();
                            for (int i = 0; i < clothPieceCheckRights.size(); i++) {
                                grString.add(clothPieceCheckRights.get(i).getSerNo());
                                grOrderIdString.add(clothPieceCheckRights.get(i).getOrderId());
                            }
                            grAdapter = new ClothPieceSearchGrAdapter(grString, ClothSizeSearchActivity.this, -1);
                            gr.setAdapter(grAdapter);
                            lvRight.setAdapter(null);
                        }
                    } else {
                        gr.setAdapter(null);
                        lvRight.setAdapter(null);
                    }
                    break;
                case MSG_DetaiInfoOver:
                    //显示到orderListGrid中;
                    if (detailJSON != null && detailJSON.length() > 0) {
                        List<ClothPieceCheckRight> clothPieceCheckRights = new Gson().fromJson(String.valueOf(detailJSON), new TypeToken<List<ClothPieceCheckRight>>() {
                        }.getType());
                        if (clothPieceCheckRights != null) {
                            rights.clear();
                            rights.addAll(clothPieceCheckRights);
                            clothPieceSearchRightLvAdapter = new ClothSizeSearchRightLvAdapter(rights, ClothSizeSearchActivity.this);
                            lvRight.setAdapter(clothPieceSearchRightLvAdapter);
                        }
                    } else {
                        lvRight.setAdapter(null);
                    }
                    break;
                case MSG_ErrMessage:
                    lefts.clear();
                    clothPieceSearchLeftLvAdapter.notifyDataSetChanged();

                    lvRight.setAdapter(null);
                    gr.setAdapter(null);
                    Bundle bundle = msg.getData();
                    System.out.println(bundle);
                    String SQLExcept = bundle.getString("SQLExcept");
                    String SQLMessage = bundle.getString("SQLMessage");
                    Toast.makeText(ClothSizeSearchActivity.this, SQLMessage, Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:" + SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OperType") == true) {
                            //呼叫信息及库存警告
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("GetOrder") == true) {
                                detailJSON = jsonArray;
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = MSG_DetailOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("GetOrderDe") == true) {
                                detailJSON = jsonArray;
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = MSG_DetailDEOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("GetOrderInfo") == true) {
                                detailJSON = jsonArray;
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = MSG_DetaiInfoOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept")) {
                            System.out.println("Enter SqlExcept");
                            //显示预排单;
                            Message msg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("SQLExcept", jsonArray.optJSONObject(0).getString("SQLExcept"));
                            bundle.putString("SQLMessage", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            msg.what = MSG_ErrMessage;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                    } else {
                        //显示预排单;
                        Message msg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("SQLExcept", "ErrInfo");
                        bundle.putString("SQLMessage", "未返回任何数据!");
                        msg.setData(bundle);
                        msg.what = MSG_ErrMessage;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();

    }
}
